﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Quellenverwaltung.Data.Source;
using Quellenverwaltung.SRU;

namespace Quellenverwaltung.Threads
{
    public class SearchSRUProcess
    {
        public event EventHandler<SearchSRUProcessArgs> ResultFound;
        public SRU.CQLBuilder CqlBuilder { get; set; }
        public SRU.Service Service { get; set; }
        private Word.Configuration configuration;

        public SearchSRUProcess(String sruService)
        {
            configuration = Word.Configuration.getConfiguration();
            CqlBuilder = new SRU.CQLBuilder();
            this.Service = new SRU.Service(sruService);
            this.Service.sruRecordSchema = configuration.SRURecordsSchema;
        }

        /// <summary>
        /// Starts search in additional Thread.
        /// </summary>
        public void StartSearch()
        {
            ThreadStart start = new ThreadStart(delegate
            {
                SearchSRUProcessArgs args = new SearchSRUProcessArgs() { Result = this.Process() };
                this.ResultFound(this, args);
            });

            Thread t = new Thread(start);
            t.Start();
        }

        private Sources Process()
        {
            try
            {
                ServiceConsumer consumer = new ServiceConsumer(this.Service);
                Sources sources = consumer.Request(this.CqlBuilder);
                return sources;
            }
            catch (Exception ex)
            {
                Sources sources = new Sources();
                sources.Exception = ex;
                return sources;
            }
        }
    }

    /// <summary>
    /// Class to pass arguments between SearchProcess events.
    /// </summary>
    public class SearchSRUProcessArgs : EventArgs
    {
        /// <summary>
        /// Gets or sets the result.
        /// </summary>
        /// <value>
        /// The result.
        /// </value>
        public Sources Result { get; set; }
    }
}
